/*
Sort a linked list in O(n log n) time using constant space complexity.
*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *sortList(ListNode *head) {
        if (!head || head->next==NULL) return head; // 0 or 1 element
        ListNode *slow = head, *fast = head;
        while (fast->next && fast->next->next) {
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode *n2 = sortList(slow->next);
        slow->next = NULL;
        ListNode *n1 = sortList(head);
        return merge2List(n1, n2);
    }
private:
    ListNode *merge2List(ListNode *l1, ListNode *l2) {
        ListNode head(-1), *ptr = &head;
        while (l1 && l2) {
            if (l1->val <= l2->val) {ptr->next = l1; l1=l1->next;}
            else {ptr->next = l2; l2=l2->next; }
            ptr = ptr->next;
        }
        if (l1) ptr->next = l1;
        if (l2) ptr->next = l2;
        return head.next;
    }
};
